<template>
  <div class="main">
    <new-earth-comp
      ref="newEarthComp"
      v-show="true"
      :ticketLineStatus="ticketLineStatus"
      :full-screen-comp.sync="fullScreenComp"
      :is-show-aircraft-comp="isShowAircraft"
      @openNest="openNest($event)"
      @openQj="openQj"
    />
    <KanBanNavBox />
    <LeftKanBan v-show="isShowElseKanBan" />
    <RightKanBan
      ref="rightKanBan"
      v-show="isShowElseKanBan"
      :ticketLineStatus="ticketLineStatus"
      @ticketLineStatusChange="ticketLineStatusChange"
      @getIssuesList="getIssuesList"
    />
    <BottomKanBan
      ref="refBottomMenu"
      v-show="isShowElseKanBan"
      :ticketLineStatus="ticketLineStatus"
      @ticketLineStatusChange="ticketLineStatusChange"
      @openNest="openNest($event)"
    />
    <nest-and-aircraft-comp
      v-if="isShowNestInfo"
      :nest-id="selectedNestId"
      :full-screen-comp="fullScreenComp"
      @closeNest="closeNest"
    />
    <PanoramaComp
      ref="panorama"
      v-if="isShowQj"
      :selectPanorama="selectPanorama"
      :QjList="QjList"
      :QJLocateParams="QJLocateParams"
      :selectPanoramaIndex="selectPanoramaIndex"
    >
    </PanoramaComp>

    <div v-if="false" class="testBtn" @click="test">
      <span>功能测试</span>
    </div>
  </div>
</template>
<script>
import NewEarthComp from "./components/newEarthComp.vue";
import KanBanNavBox from "./components/kanbannavbox.vue";
import LeftKanBan from "./components/leftkanban.vue";
import RightKanBan from "./components/rightkanban.vue";
import BottomKanBan from "./components/bottomkanban.vue";
import NestAndAircraftComp from "./components/NestAndAircraftComp";
import PanoramaComp from "./components/panoramaComp";

import socketUtil from "@/utils/socketUtil";

export default {
  name: "Kanban",
  components: {
    NestAndAircraftComp,
    NewEarthComp,
    KanBanNavBox,
    LeftKanBan,
    RightKanBan,
    BottomKanBan,
    PanoramaComp,
  },
  data() {
    return {
      isShowElseKanBan: true, // 显示其他看板组件
      isShowNestInfo: false,
      isShowExternalVideo: false,
      isShowQj: false, // 全景
      fullScreenComp: 0, // 0 地图；1 机巢；2 无人机 ;3 机巢内部; 4 全景
      isShowAircraft: true,
      selectedNestId: "",
      loading: null,
      selectPanorama: "", // 选中全景
      QjList: [], // 全景列表
      selectPanoramaIndex: "", // 全景中 选中的全景index
      // 全景点位参数
      QJLocateParams: { issues: [], pa_info: [] },
      issueList: [], // 问题列表
      ifLayerSee: true, // 是否可见 图标

      ticketLineStatus: false, // 是否指点任务

      userAuthor: null,
    };
  },
  created() {
    this.userAuthor = this.$store.getters.userAuth;
  },
  mounted() {
    // document.getElementsByClassName("app-main2")[0].style['height'] = 'calc(100vh - 50px)';
    // todo  模拟获取机巢信息，并保存到store
    // this.mockRequestNestList()
    if (
      this.userAuthor?.warning?.query?.have_auth ||
      this.userAuthor?.order?.query?.have_auth ||
      this.userAuthor?.search_photo?.query?.have_auth
    ) {
      this.loading = this.$loading({
        lock: true,
        text: "数据加载",
        spinner: "el-icon-loading",
        background: "rgba(3, 26, 56, 0.8)",
        customClass: "loadingclass",
      });
    }
    this.initBus();
    this.initSocket();
    window.onbeforeunload = (e) => {
      this.handleSession();
      return null;
    };
  },
  methods: {
    initBus() {
      var that = this;
      this.$bus.on("CloseLoading", (data) => {
        console.log("关闭loading-------------------------------------");
        that.loading.close();
        that.$bus.on("change_full_screen", (data) => {
          console.log("receive change_full_screen", data);
          that.fullScreenComp = data;
        });
      });

      this.$bus.on("openNest", (data) => {
        that.openNest(data);
      });

      this.$bus.on("changePanorama", (panorama) => {
        console.log(panorama);
        if (!panorama) {
          this.$message.warning("暂无全景数据");
          return;
        }
        this.selectPanorama = panorama;
      });

      // 选中全景
      this.$bus.on("qjListIndex", (index) => {
        if (this.$refs.panorama) {
          this.$refs.panorama.selectIndex = index;
        } else {
          this.selectPanoramaIndex = index;
        }
      });
    },
    initSocket() {
      console.log("initSocket");
      let that = this;
      window.KBSocket = socketUtil.getInstance();
      // console.log("socketUtil", KBSocket);
      KBSocket?.io.on("nest_state", (res) => {
        // console.log("nest_state", res);
        let data = {
          abnormal: { count: 0, list: [] },
          offline: { count: 0, list: [] },
          online: { count: 0, list: [] },
          flying: { count: 0, list: [] },
          maintenance: { count: 0, list: [] },
        };
        let weatherData = {
          abnormal: { count: 0, list: [] },
          offline: { count: 0, list: [] },
          online: { count: 0, list: [] },
          flying: { count: 0, list: [] },
          maintenance: { count: 0, list: [] },
        };
        res.forEach((nest) => {
          let findNest = this.$store.getters.nestList.find((GNest) => {
            return GNest.nest_code == nest.nest_code;
          });
          if (!!findNest) {
            for (let key in data) {
              nest.nest_name = findNest.nest_name;
              if (nest.nest_state == key) {
                data[key].list.push({
                  nest_code: nest.nest_code,
                  nest_name: nest.nest_name,
                  city: findNest?.city,
                  quantity: nest.quantity,
                });
              }
              data[key].count = data[key].list.length;
            }
            for (let key in weatherData) {
              nest.nest_name = findNest.nest_name;
              if (nest.nest_state == key) {
                weatherData[key].list.push(nest);
              }
              weatherData[key].count = weatherData[key].list.length;
            }
          } else {
            // console.log("对不上的机场", findNest, nest);
          }
        });
        let getterNestList = that.$store.getters.nestStateList;
        if (!!data) {
          if (JSON.stringify(getterNestList) != JSON.stringify(data)) {
            // console.log("有变化");
            that.$store.commit("SAVE_NEST_STATE_LIST", data);
            that.$bus.emit("nestStatusListUpdate", data);
            that.$bus.emit("menuNestStatusListUpdate", data);
          } else {
            // console.log("无变化");
          }
        }

        that.$bus.emit("nestWeatherUpdate", weatherData);
      });
    },
    resetVideoPosition(isShowAircraft) {
      this.isShowAircraft = isShowAircraft;
    },
    //
    openNest(event) {
      console.log("openNestopenNest", event);
      //
      if (event.length === 2) {
        this.fullScreenComp = event[1] === true ? 2 : 0;
        this.selectedNestId = event[0].nest_code;
      } else {
        this.fullScreenComp = 0;
        this.selectedNestId = event.nest_code;
      }
      console.log("openNestopenNest1", this.fullScreenComp);
      console.log("openNestopenNest2", this.selectedNestId);

      this.isShowNestInfo = true;
      this.isShowElseKanBan = false;
    },
    closeNest() {
      // this.$router.push({ query: {} })
      // this.$router.push(`${this.$route.path}`)
      // todo 删除参数 不刷新
      this.isShowNestInfo = false;
      this.isShowElseKanBan = true;
      this.fullScreenComp = 0;
    },
    // 打开全景
    openQj(qjList, qjIssueList, position) {
      let that = this;
      // 切换至预警信息
      this.$refs.rightKanBan.changeModule(4);

      if (nowQJMarkLayer) {
        CesiumUtil.LayerRemoveAll(nowQJMarkLayer);
      }
      // 打上图标
      const QJMarkOption = {
        id: "nowQJMark",
        // name: "全景眼",
        type: "QJMark",
        longitude: position[0],
        latitude: position[1],
        height: position[2] ? position[2] : 5,
        scale: 0.05,
        pixelOffset: [0.0, 0.0],
        distanceShow: [100, 8000],
        icon: "https://fsimage.guihuao.com/geodata/png/file_2023_06_14_08_58_21_c0984f08.png",
      };
      const QJEyeVisualAngleOption = {
        id: "nowQJEyeVisualAngle",
        // name: "全景眼范围",
        type: "QJEyeVisualAngle",
        longitude: position[0],
        latitude: position[1],
        height: position[2] ? position[2] - 1 : 4,
        scale: 0.3,
        rotation: Cesium.Math.toRadians(-90),
        pixelOffset: [0.0, 0.0],
        distanceShow: [100, 8000],
        icon: require("@/assets/EyeVisualAngle.png"),
      };
      window.QJMark = CesiumUtil.AddMark(QJMarkOption, nowQJMarkLayer);
      window.EyeVisualAngle = CesiumUtil.AddMark(
        QJEyeVisualAngleOption,
        nowQJMarkLayer
      );
      QJMark.billboard.rotation = Cesium.Math.toRadians(-90);
      EyeVisualAngle.billboard.rotation = Cesium.Math.toRadians(-90);
      let scene = viewer.scene;
      // scene.screenSpaceCameraController.enableRotate = false;// 移动
      scene.screenSpaceCameraController.enableTranslate = false;
      scene.screenSpaceCameraController.enableTilt = false; // 旋转

      this.$nextTick(() => {
        this.isShowQj = true;
        this.fullScreenComp = 4;
        this.QjList = qjList;
        this.QJLocateParams = { issues: [], pa_info: [] };
        this.QJLocateParams.issues = qjIssueList;
        qjList.forEach((qj) => {
          let positions = Cesium.Cartographic.fromDegrees(
            +qj.position[0],
            +qj.position[1]
          );
          let height = 0;
          Promise.resolve(
            Cesium.sampleTerrain(viewer.terrainProvider, 12, [positions])
          ).then(function (upDatedPositions) {
            height = upDatedPositions[0].height;

            let location = [height, +qj.position[0], +qj.position[1]];
            qj.scenes.forEach((scene) => {
              that.QJLocateParams.pa_info.push({
                panoramas_id: scene.qj.split("?scene_id=")[1],
                panoramas_name: qj.name,
                location: location,
              });
            });
          });
        });
        // 隐藏底部指点按钮
        this.$bus.emit("bottomButtonShow", false);
        // 底部图层关闭
        this.$bus.emit("QJLayerShow", false);
        // 隐藏机巢状态
        this.$bus.emit("nestWrapBtnShow", false);
        // 隐藏地图上所有图标
        if (this.ifLayerSee) {
          this.ifLayerSee = false;
          WinLayerListNew = [];
          WINLayerList.forEach((layer) => {
            if (layer && layer.show) {
              layer.show = false;
              WinLayerListNew.push(layer);
            }
          });
        }
      });
    },
    // 关闭全景
    closeQj() {
      console.log("closeQjcloseQj");
      this.isShowQj = false;
      // this.fullScreenComp = 2;
      //显示底部指点按钮
      this.$bus.emit("bottomButtonShow", true);
      // 底部图层开启
      this.$bus.emit("QJLayerShow", true);
      // 显示机巢状态
      this.$bus.emit("nestWrapBtnShow", true);
      // 显示地图上所有图标
      if (!this.ifLayerSee) {
        WinLayerListNew.forEach((layer) => {
          layer.show = true;
        });
        WinLayerListNew = [];
        this.ifLayerSee = true;
      }

      CesiumUtil.LayerRemoveAll(nowQJMarkLayer);
      let scene = viewer.scene;
      // scene.screenSpaceCameraController.enableRotate = true;
      // scene.screenSpaceCameraController.enableTranslate = true;
      scene.screenSpaceCameraController.enableTilt = true;
    },
    // ! 获取问题点
    getIssuesList(issue) {
      this.issueList = issue;
    },
    handleSession() {
      sessionStorage.setItem("rightSearchHistory", "");
      sessionStorage.setItem("view3SearchHistory", "");
      sessionStorage.setItem("view5SearchHistory", "");
      sessionStorage.setItem("view3SelectedData", "");
    },
    // 指点任务状态
    ticketLineStatusChange(flag) {
      console.log("ticketFlag", flag);
      if (flag) {
        // 前往指点任务
        this.$refs.rightKanBan.changeModule(5);
        this.$nextTick(() => {
          this.$refs.rightKanBan.$refs?.view5.boxStatusChange(2);
        });
      } else {
        this.$refs.rightKanBan.$refs?.view5?.boxStatusChange(1);
      }
    },
  },
  watch: {
    fullScreenComp(newVal, oldVal) {
      console.log("fullScreenComp NestAndA2", newVal);
      // this.$emit('update:fullScreenComp', newVal)
    },
  },
  destroyed() {
    // document.getElementsByClassName("app-main2")[0].style['height'] = 'auto';
    sessionStorage.setItem("view3SelectedData", null);
    this.$bus.$off();
  },
};
</script>
<style>
.el-loading-spinner i {
  color: #ffffff;
}

.el-loading-spinner .el-loading-text {
  font-size: 18px;
}
</style>
<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  background-image: radial-gradient(rgb(23 23 25), #0d1c33);
}

.testBtn {
  color: white;
  border: #0d1c33 1px solid;
  padding: 4px;
  position: absolute;
  left: 400px;
  bottom: 50px;
  cursor: pointer;
  z-index: 2000;
}
</style>
